<?php

namespace app\api\controller\common;

use think\Controller;
use app\api\model\Role as RoleModel;
use app\api\model\Admin as AdminModel;
use app\api\model\Auth as AuthModel;
use app\api\controller\common\CommonPlus;
use think\Db;

/**
 * 公共类
 * 不走权限验证的接口可以放这里
 */
class Index extends Controller
{

    public function upupupup(){
        if (request()->isPost()) {
            $post = input('post.');
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : 0;
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $company=db($tabName)->where(['id'=>$id])->find();
            if(!$company){
                return json(array('code' => '0', 'msg' => '错误'));
            }
            $booth=db('booth')->where(['agent_id'=>$id,'is_delete'=>0,'exhibition_id'=>$exhibition_id])->field('id')->select();
            $contract=db('contract')->where(['id_zs'=>$id,'is_delete'=>0,'id_zhui'=>$exhibition_id])->field('id')->select();
            if(count($booth)==1 && count($contract)==1){
//                var_dump($contract['id']);die();
                $res=db('contract')->where(['id'=>$contract[0]['id']])->update(['id_zwei'=>$booth[0]['id']]);
                if(!$res){
                    return json(array('code' => '0', 'msg' => '失败'));
                }
                return json(array('code' => '1', 'msg' => '操作陈宫'));
            }else{
                return json(array('code' => '0', 'msg' => '数据多了'));
            }

            } else {
                return json(array('code' => '0', 'msg' => '账号不存在'));
            }
    }

    /**
     * 登录
     *
     * @return void
     */
    public function login()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $admin = model('admin')->where(['account' => $post['account']])->find();
            if ($admin) {
                if ($admin['password'] === md5(md5($post['password']) . $admin['salt'])) {
                    unset($admin['password'], $admin['salt']);
                    session('admin', $admin);
                    write_admin_log('登录');
                    return json(array('code' => '1', 'msg' => '登录成功', 'data' => $admin));
                } else {
                    return json(array('code' => '0', 'msg' => '密码错误'));
                }
            } else {
                return json(array('code' => '0', 'msg' => '账号不存在'));
            }
        }
    }

    /**
     * 退出
     *
     * @return void
     */
    public function logout()
    {
        write_admin_log('退出');
        session('admin', null);
        return json(array('code' => '1', 'msg' => '退出成功'));
    }

    /**
     * 获取权限树
     *
     * @return void
     */
    public function getAuthTree()
    {
        if (!session('?admin')) {
            return json(array('code' => '-1', 'msg' => '请先登录！'));
        }
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        if ($admin['is_super'] != 1) {
            $roleIds = [];
            $arr = collection($admin->role)->toArray();
            foreach ($arr as $v) {
                if ($v['status'] == 1) {
                    array_push($roleIds, $v['id']);
                }
            }
            $roleIdsStr = implode(',', $roleIds);
            $role = RoleModel::all(['id' => ['in', $roleIdsStr], 'status' => 1], 'auth');
            $roleArr = collection($role)->toArray();
            $authArr = [];
            foreach ($roleArr as $v) {
                foreach ($v['auth'] as $vv) {
                    $d = $vv;
                    unset($d['create_time'], $d['update_time'], $d['pivot']);
                    // $vv['level']==1 之前无。修复首页菜单 无法勾选
                    if ($vv['status'] == 1 && ($vv['level'] == 3 || $vv['level']==1)) {
                        array_push($authArr, $d);
                    }
                }
            }
            $pids = [];

            $ppids = [];
            foreach ($authArr as $v) {
                deep_in_array($v['parent_id'], $pids) ? null : array_push($pids, $v['parent_id']);
            }
            $pAuth = authModel::all(['id' => ['in', $pids]]);
            $pAuthsArr = collection($pAuth)->toArray();

            $ppids = [];
            foreach ($pAuthsArr as $k => $v) {
                unset($pAuthsArr[$k]['create_time'], $pAuthsArr[$k]['update_time']);
                deep_in_array($v['parent_id'], $pids) ? null : array_push($ppids, $v['parent_id']);
            }
            $ppAuth = authModel::all(['id' => ['in', $ppids]]);
            $ppAuthsArr = collection($ppAuth)->toArray();
            foreach ($ppAuthsArr as $k => $v) {
                unset($ppAuthsArr[$k]['create_time'], $ppAuthsArr[$k]['update_time']);
            }

            $newAuthArr= array_unique(array_merge($ppAuthsArr, $pAuthsArr, $authArr), SORT_REGULAR);

            //根据字段sort对数组$authArr进行降序排列
            $sort = array_column($newAuthArr, 'sort');
            array_multisort($sort, SORT_DESC, $newAuthArr);
            $tree = list_to_tree($newAuthArr);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $tree));
        } else {
            $authList = AuthModel::all();
            $authList = collection($authList)->toArray();
            $authArr = [];
            foreach ($authList as $vv) {
                $d = $vv;
                unset($d['create_time'], $d['update_time']);
                if ($vv['status'] == 1 && $vv['level'] < 3) {
                    array_push($authArr, $d);
                }
            }
            //根据字段sort对数组$authArr进行降序排列
            $sort = array_column($authArr, 'sort');
            array_multisort($sort, SORT_DESC, $authArr);
            $tree = list_to_tree($authArr);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $tree));
        }
    }

    /**
     * 上传img
     * @return void
     */
    public function uploadImg()
    {
        $res = upload(1);
        return json($res);
    }
    /**
     * 上传excel
     * @return void
     */
    public function uploadExcel()
    {
        $res = upload(2);
        return json($res);
    }
    /**
     * 上传word
     * @return void
     */
    public function uploadWord()
    {
        $res = upload(3);
        return json($res);
    }

    /**
     * 上传合同模板
     * @return void
     */
    public function uploadTemplate()
    {
        $res = upload(4);
        return json($res);
    }

    /**
     * 上传合同模板
     * @return void
     */
    public function uploadFile()
    {
        $res = upload(5);
        return json($res);
    }

    /**
     * 上传合同模板
     * @return void
     */
    public function uploadVideo()
    {
        $res = upload(6);
        return json($res);
    }

    /**
     * 获取门店列表
     * @return \think\response\Json|void
     */
    public function storeList()
    {
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        $where['is_delete'] = 0;
        $where['status'] = 0;
        if($admin['is_super']!=1){
            $where['id'] = $admin['org_id'];
        }
        $r=db('store')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }

    //技师列表
    public function technicianList()
    {
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        $where['is_delete'] = 0;
        $where['status'] = 0;
        $where['is_technician'] = 1;
        if($admin['is_super']!=1){
            $where['store_id'] = $admin['org_id'];
        }
        $r=db('technician')->where($where)->select();
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);
    }


    //获取管理员列表
    /**
     * 获取当前管理员展会列表
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getUserExhib(){
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        #判断是否是管理员
        $role_id = db('admin_role')->where(['admin_id'=>$admin['id']])->value('role_id');
        if(!$role_id&&$admin['is_super']==0){
            return json(['code'=>0,'msg'=>'角色不存在']);
        }
        //如果是超级管理
        $where['is_delete'] = 0;
        $data = db('exhibition')->order('id desc')->where($where)->select();
        if($admin['is_super']==0){
//            //如果是普通管理员查组织内的所有人员
//            if($role_id){
//                $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
//                if(!$is_gl){
//                    //如果是普通人员只查询关联的展会
//
//                }else{
//                    //查询组织id
//                    $w['org_id_tree'] = ['like', "%".$admin['org_id']."%"];
//                    $perList=db('admin')->field('id')->where($w)->select();
//                    $arr=[];
//                    foreach ($data as &$v){
//                        foreach ($perList as &$vv){
//                            if(($v['is_company'] == $vv['id']) || ($v['customer_manager'] == $vv['id']) || ($v['merchants_manager'] == $vv['id']) || (strpos($v['persons'],strval($vv['id'])) !== false)){
//                                array_push($arr,$v);
//                            }
//                        }
//                    }
//                    unset($v,$vv);
//                    $data=$this->uniquArr($arr);
//                }
//            }

            $where['persons'] =  ['like', "%".$admin['id']."%"];;
            $data= db('exhibition')->order('id desc')->where($where)->select();
        }
        return json(['code'=>1,'msg'=>'success','data'=>$data]);
    }


    /**
     * 素材列表
     * @author 01
     * @email 319204520@qq.com
     * @date 2023-02-12 23:19
     */
    public function main_list()
    {
        $data = $this->request->param();
        $this->model = new \app\api\model\Media();

        $list = $this->model->getList();

        $this->success('获取成功', '', $list);
    }



    public function uniquArr($array){
        $result = array();
        foreach($array as $k=>$val){
            $code = false;
            foreach($result as $_val){
                if($_val['id'] == $val['id']){
                    $code = true;
                    break;
                }
            }
            if(!$code){
                $result[]=$val;
            }
        }
        return $result;
    }

    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }
    //添加到展商列表
    /**
     * 业务员自提数据----添加到展商列表-复制私海-李
     * 公海表 status 改为3自提
     */

    public function gives(){
        $com =new CommonPlus();
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        $cid = $this->request->param('id');//公司id
        $exhibition_id = $this->request->param('exhibition_id'); //展会id
        $member_id = $admin['id']; //此处稍作改动，自提就是自己给自己加展商所以不用传的--李
        $sale_id = $admin['id'];
        $back=2;
        if(empty($exhibition_id)){
            return json(['code'=>0,'msg'=>'展会数据有误']);
        }
        $tabName=$this->getTabName($exhibition_id);

        $where['id'] = $cid;
        $info =  Db::name('company')->where($where)->find();
        if(!$info){
            return json(['code'=>0,'msg'=>'企业库数据有误']);
        }
        $company=$info;
        $protectTotal=db($tabName)->field('company_id1')->where(['member_id'=>$member_id,'status'=>array('lt',5)])->select();
        $protectIds=array_column($protectTotal,'company_id1');
        $oldTotal=db('company_label')->where(['company_id'=>array('in',implode(",", $protectIds)),'label'=>'老展商'])->count('DISTINCT company_id');
        $counts=count($protectTotal)-$oldTotal;
        $max_number=db('max_number')->where(['uid'=>$member_id,'exhibition_id'=>$exhibition_id])->value('max_number');
        $max_number=$max_number?$max_number:30;
        if(($counts+1)>$max_number){
            return json(['code'=>0,'msg'=>'操作失败！已超过最大展商保护数量,现剩余'.($max_number-$counts)."个名额"]);
        }
          $ghInfo =  Db::name($tabName)->where(['company_name'=>$company['company_name']])->find();
          if($ghInfo){
              if($ghInfo['member_id']>0){
                  db('company_error')->insert(['create_time'=>time(),'company_id'=>$ghInfo['id'],'member_id'=>$member_id,'exhibition_id'=>$exhibition_id]);
                 return json(['code'=>0,'msg'=>'此数据已分配,请联系管理员！']);
              }else{
                $ghResult=Db::name($tabName)->where(['id'=>$ghInfo['id']])->update(['member_id'=>$member_id,'back'=>2,'protection_time'=>time()]);
                if(!$ghResult){
                    return json(['code'=>0,'msg'=>'公海数据同步失败']);
                }
                $com->companyLog($exhibition_id,'潜在展商-将展商进行自提保护',$member_id,$ghInfo['id']);
                return json(['code'=>1,'msg'=>'操作成功']);
              }
          }
        unset($company['id']);
        unset($company['mail_address']);
        unset($company['mail_mobile']);
        unset($company['mail_person']);
        $company['member_id']=$member_id;
        $company['sale_id']=$sale_id;
        $company['back']=$back;
        $company['update_time']=time();
        $company['create_time']=time();
        $company['company_id1']=$cid;
        $result=db($tabName)->insertGetId($company);
        if(!$result){
            return json(['code'=>0,'msg'=>'公海数据同步失败']);
        }
        $com->companyLog($exhibition_id,'潜在展商-将展商进行自提保护',$member_id,$result);
        return json(['code'=>1,'msg'=>'操作成功']);
    }



    /**
     * 新增企业
     * @return \think\response\Json|void
     * 1：有基础库，企业库。  暂时先这么搞
     */
    public function addCompany()
    {
        //==common
        $com =new CommonPlus();
        $admin = session('admin');
        $admin = AdminModel::get(['id' => $admin['id']]);
        $create_uid  = $admin['id'];

        $selfcontent = $this->request->param('selfcontent'); //自定义表单 理论上只有新增 才有 。。让前台隐藏吧

        //
        $company_name = $this->request->param('company_name'); //公司中文名
        $company_address = $this->request->param('company_address'); //地址
        $company_name_en = $this->request->param('company_name_en'); //
        $company_describe = $this->request->param('company_describe'); //简介
        $tel = $this->request->param('tel');   //固定电话
        $link = $this->request->param('link');
        $product_brand = $this->request->param('product_brand');   //产品品牌
        $application_area = $this->request->param('application_area');    //应用领域  字段？？ 有两个
        $mobile = $this->request->param('mobile');
        $email = $this->request->param('email');
        $qq = $this->request->param('qq');
        $wechat = $this->request->param('wechat');
        $msn = $this->request->param('msn');
        $product_describe = $this->request->param('product_describe');   //产品介绍
        $product_positioning = $this->request->param('product_positioning');  //定位
        $product_keyword = $this->request->param('product_keyword');    //关键字
        //$application_area = $this->request->param('application_area');  //应用领域 下拉框？还是？？ 两个字段页面
        $remark = $this->request->param('remark');
        $category_id = $this->request->param('category_id');  //一级 分类
        $second_category_id = $this->request->param('second_category_id');     //二级 分类
        $product = $this->request->param('product');  //产品
        $capacitys = $this->request->param('capacitys');  //年产能
        $sale_fee = $this->request->param('sale_fee'); //年销售总额:
        $sale_pb = $this->request->param('sale_pb'); //pb年PB销售占比
        $pb_time = $this->request->param('pb_time');  //进入pb时间
        $pb_customer = $this->request->param('pb_customer'); //主要pb客户
        $country = $this->request->param('country');
        $country_code = $this->request->param('country_code'); //国家代码
        $province = $this->request->param('province');  //省份
        $area = $this->request->param('area'); //区域
        $area_city = $this->request->param('area_city');  //地级市
        $area_town = $this->request->param('area_town'); //县市
        // 个人信息
        $surname_cn = $this->request->param('surname_cn');  //中文 姓
        $surname_en = $this->request->param('surname_en');  //英文 姓
        $name_cn = $this->request->param('name_cn');     // 中文名
        $name_en = $this->request->param('name_en'); // 英文名
        $call_name_cn = $this->request->param('call_name_cn'); // 称谓 中
        $call_name_en = $this->request->param('call_name_en'); //称谓 英文
        $positions_cn = $this->request->param('positions_cn');  // 职务 中
        $positions_en = $this->request->param('positions_en'); //职务
        $department_cn = $this->request->param('department_cn'); // 部门中
        $department_en = $this->request->param('department_en'); //部门 英
        $tel_person_code = $this->request->param('tel_person_code');  // 区号
        $tel_person = $this->request->param('tel_person'); //
        $tel_person_history = $this->request->param('tel_person_history'); //原始号码
        $mobile_person = $this->request->param('mobile_person'); //个人手机
        $fax_person = $this->request->param('fax_person');  // 传真
        $fax_history = $this->request->param('fax_history');  // 原始传真
        $email_person = $this->request->param('email_person');  // email 个人
        $mobile_status = $this->request->param('mobile_status');  // 电话已核对 是需要填写数字？？
        $addr_person = $this->request->param('addr_person');  // 地址 个人
        $info_level = $this->request->param('info_level'); // 信息质量
        $data_from = $this->request->param('data_from');  // 数据来源
        $duties = $this->request->param('duties');  // 岗位职责
        $job_nature = $this->request->param('job_nature');  // 工作性质
        $company_ID = $this->request->param('company_ID'); //公司id
        $persontype = $this->request->param('persontype'); //人员类别
        $industrys = $this->request->param('industrys'); // 行业
        $company_nature = $this->request->param('company_nature');  // 公司性质

        $qualifications = $this->request->param('qualifications');  // 资质
        $company_form = $this->request->param('company_form');  // 公司形态
        $business = $this->request->param('business');  // 业务性质
        $system_status = $this->request->param('system_status');  // 系统状态
        $id_card = $this->request->param('id_card');  // 证件号码
        $chau = $this->request->param('chau');  // 所属洲
        $ishzselfbrander = $this->request->param('ishzselfbrander');  // 是否合作过自有品牌客户
        $ishzselfbrand = $this->request->param('ishzselfbrand');  // 是否合作过自有品牌
        $label = $this->request->param('label');  //
//        $label_2 = $this->request->param('label_2');  //
        //手机号码验证
        $preg_phone="/^1[34578]\d{9}$/";
        if(!preg_match($preg_phone,$mobile)){
            return json(['code' => 0, 'msg' => '手机号码格式错误!']);
        }
        $preg_patter = "/^(0(10|21|22|23|[1-9][0-9]{2})(-|))?[0-9]{7,8}$/";
        if(!preg_match($preg_patter,$tel)){
            return json(['code' => 0, 'msg' => '座机号码格式错误!']);
        }

        $data = array(
            'create_uid' => $create_uid, 'remark' => $remark,'update_time' => time(), 'create_time' => time(), 'company_name' => $company_name,
            'company_name_en' => $company_name_en, 'company_describe' => $company_describe, 'tel' => $tel, 'link' => $link,
            'product_brand' => $product_brand, 'application_area' => $application_area, 'mobile' => $mobile,
            'email' => $email, 'qq' => $qq, 'wechat' => $wechat, 'msn' => $msn, 'product_describe' => $product_describe,
            'product_positioning' => $product_positioning, 'product_keyword' => $product_keyword, 'remark' => $remark,
            'category_id' => $category_id, 'second_category_id' => $second_category_id, 'product' => $product,
            'capacitys' => $capacitys, 'sale_fee' => $sale_fee, 'sale_pb' => $sale_pb, 'pb_time' => $pb_time,
            'pb_customer' => $pb_customer, 'country' => $country, 'country_code' => $country_code, 'province' => $province,
            'area' => $area, 'area_city' => $area_city, 'area_town' => $area_town,
            'surname_cn' => $surname_cn, 'name_cn' => $name_cn, 'surname_en' => $surname_en,
            'name_en' => $name_en, 'call_name_cn' => $call_name_cn, 'call_name_en' => $call_name_en,
            'positions_cn' => $positions_cn, 'positions_en' => $positions_en, 'department_cn' => $department_cn,
            'department_en' => $department_en, 'tel_person_code' => $tel_person_code, 'tel_person' => $tel_person,
            'tel_person_history' => $tel_person_history, 'mobile_person' => $mobile_person, 'fax_person' => $fax_person,
            'fax_history' => $fax_history, 'email_person' => $email_person, 'mobile_status' => $mobile_status,
            'addr_person' => $addr_person, 'info_level' => $info_level, 'data_from' => $data_from,
            'duties' => $duties, 'job_nature' => $job_nature, 'company_ID' => $company_ID,
            'persontype' => $persontype, 'industrys' => $industrys, 'company_nature' => $company_nature, 'qualifications' => $qualifications,
            'company_form' => $company_form, 'business' => $business, 'system_status' => $system_status,
            'id_card' => $id_card, 'chau' => $chau, 'ishzselfbrander' => $ishzselfbrander, 'ishzselfbrand' => $ishzselfbrand, 'selfcontent' => $selfcontent,
            'label' => $label, 'company_address'=>$company_address
        );


        // 验证电话 企业  排除 删除
        if (!empty($company_name)) {
            $where = ['company_name' => $company_name, 'is_delete' => 0];
            $ckinfo = model('Companymgr')->countWhere($where);
            $msg = "公司名已存在!";

            if ($ckinfo > 0) {
                return json(['code' => 0, 'msg' => $msg]);
            }
        } else {
            return json(['code' => 0, 'msg' => '公司名称不能为空']);
        }

        if (!empty($tel)) {
            $where = ['tel' => $tel, 'is_delete' => 0];
            $ckinfo = model('Companymgr')->countWhere($where);
            $msg = "公司固定电话号码已存在!";

            if ($ckinfo > 0) {
                return json(['code' => 0, 'msg' => $msg]);
            }
        } else {
            return json(['code' => 0, 'msg' => '公司固定电话不能为空']);
        }

        if (!empty($mobile)) {
            $where = ['mobile' => $mobile, 'is_delete' => 0];
            $ckinfo = model('Companymgr')->countWhere($where);
            $msg = "公司手机号码已存在!";

            if ($ckinfo > 0) {
                return json(['code' => 0, 'msg' => $msg]);
            }
        } else {
            return json(['code' => 0, 'msg' => '公司手机号码不能为空']);
        }


        //  Yanzheng ed   适当放松的



        // var_dump ($data);die;
        $r =  model('Companymgr')->insertData($data);
        if (!$r) {
            return json(['code' => 0,'msg' => '操作失败，请重试']);
        }
        $com->companyLog('',$company_name.'新增至企业基础库',$create_uid,'');
        return json(['code' => 1,'data'=> $r, 'msg' => '操作成功']);
    }


    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $where['is_super'] = 0;

            if ($orgId != 0) {
                $role_id = db('admin_role')->where(['admin_id'=>$admin['id']])->value('role_id');
                $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
                if($is_gl == 1){
                    $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
                }else{
                    $where['a.id']=$admin['id'];
                }
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_organization b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.org_name,a.create_time,a.update_time')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    /**
     * 获取此页面所有下拉
     *params 要查询的表名 ，主级需预先存表，防止错误不返回
     */

    public function getQyFormAllxla()
    {
        $comp = new CommonPlus();
        $params = array('tbarrs' => array('xiala_gsxz', 'xiala_gsxt', 'xiala_gslevel', 'xiala_sshy', 'xiala_ywxz'));

        $list = $comp->selAll_xla_BytypeF1('gsxz', $params);
        if (!$list) {
            return json(['code' => 0, 'msg' => 'error', 'data' => ['list' => $list]]);
        }
        return json(['code' => 1, 'msg' => 'success', 'data' => ['list' => $list]]);
    }

    //menu菜单保存与跟新
    public function setNavMenu(){
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            $type = isset($post['type']) && $post['type'] != '' ? $post['type'] : null;
            $nav_menu = isset($post['nav_menu']) && $post['nav_menu'] != '' ? $post['nav_menu'] : null;
            if(!$type || !$nav_menu){
                return json(array('code' => '0', 'msg' => '缺少关键主键'));
            }
            $data['create_time']=time();
            $data['type']=$type;
            $data['create_user']=$admin['id'];
            $data['nav_menu']=$nav_menu;
            $r =db('nav_menu')->field('id')->where(['type'=>$data['type'],'create_user'=>$data['create_user']])->select();
            if($r){
                $result=db('nav_menu')->where(['id'=>$r[0]['id']])->update(['nav_menu'=>$data['nav_menu']]);
            }else{
                //var_dump($data);die();
                $result = db('nav_menu')->insert($data);
            }
            if(empty($result)){
                return json(array('code' => '0', 'msg' => '操作失败'));
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }
    //menu菜单查询
    public function getNavMenu(){
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            $type = isset($post['type']) && $post['type'] != '' ? $post['type'] : null;
            if(!$type){
                return json(array('code' => '0', 'msg' => '缺少关键主键'));
            }
            $result =db('nav_menu')->field('type,id,nav_menu')->where(['type'=>$type,'create_user'=>$admin['id']])->select();
            return json(['code' => 1, 'msg' => 'success', 'data' => empty($result)?'':$result[0]]);
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    public function getTrrPage(){
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            $rule = isset($post['rule']) && $post['rule'] != '' ? $post['rule'] : null;
            if(!$rule){
                return json(array('code' => '0', 'msg' => '缺少关键主键'));
            }
            if ($admin['is_super'] != 1) {
                $roleIds = [];
                $arr = collection($admin->role)->toArray();
                foreach ($arr as $v) {
                    if ($v['status'] == 1) {
                        array_push($roleIds, $v['id']);
                    }
                }
                $roleIdsStr = implode(',', $roleIds);
                $role = RoleModel::all(['id' => ['in', $roleIdsStr], 'status' => 1], 'auth');
                $roleArr = collection($role)->toArray();
                $authArr = [];
                foreach ($roleArr as $v) {
                    foreach ($v['auth'] as $vv) {
                        $d = $vv;
                        unset($d['create_time'], $d['update_time'], $d['pivot']);
                        if ($vv['status'] == 1 && $vv['level'] == 3) {
                            array_push($authArr, $d);
                        }
                    }
                }
                $pageRoulList=[];
                foreach ($authArr as $vvv) {
                    if((strpos($vvv['rule'],strval($rule)) !== false)){
                        array_push($pageRoulList, $vvv);
                    }
                }

                return json(array('code' => '1', 'msg' => '成功', 'data' => $pageRoulList));
            } else {
                return json(array('code' => '1', 'msg' => '成功', 'data' => 'admin'));
            }
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }

    }


    //数据验证--主要针对于人员、企业、展商中心等数据处理(全部查询基础库)
    public function regBaiseInfo(){
        if (request()->isPost()) {
            $post = input('post.');
            //类型：1、公司名称 2、固定电话 3、移动电话
            $type = isset($post['type']) && $post['type'] != '' ? $post['type'] : null;
            //输入值
            $input = isset($post['input']) && $post['input'] != '' ? $post['input'] : null;
            if(!$type || !$input){
                return json(array('code' => '0', 'msg' => '缺少关键主键'));
            }

            $where['is_delete'] = 0;
            if($type == 1){$where['company_name']=$input;}
            else if($type == 2){$where['tel']=$input;}
            else if($type == 3){$where['mobile']=$input;}
            $res=db('company')->where($where)->find();
            $data=$res?1:0;
            return json(array('code' => '1','data' => $data, 'msg' => '请求成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

        //数据验证--主要针对于人员、企业、展商中心等数据处理(全部查询基础库)
        public function regBaisePerInfo()
        {
            if (request()->isPost()) {
                $post = input('post.');
                //类型：1、公司名称 2、固定电话 3、移动电话
                $type = isset($post['type']) && $post['type'] != '' ? $post['type'] : null;
                //输入值
                $input = isset($post['input']) && $post['input'] != '' ? $post['input'] : null;
                if (!$type || !$input) {
                    return json(array('code' => '0', 'msg' => '缺少关键主键'));
                }

                $where['is_delete'] = 0;
                if ($type == 1) {
                    $where['company_name'] = $input;
                } else if ($type == 2) {
                    $where['tel'] = $input;
                } else if ($type == 3) {
                    $where['mobile'] = $input;
                }
                $res = db('company_user')->where($where)->find();
                $data = $res ? 1 : 0;
                return json(array('code' => '1', 'data' => $data, 'msg' => '请求成功'));
            } else {
                return json(array('code' => '0', 'msg' => '请求失败'));
            }
        }


    //修改密码
    public function setPassword(){
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            if(empty($admin)){
                return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
            }
            //密码
            $password = isset($post['password']) && $post['password'] != '' ? $post['password'] : null;
            if(!$password || !$password){
                return json(array('code' => '0', 'msg' => '请输入密码'));
            }
            $admin = model('admin')->where(['id' => $admin['id']])->find();
            $ps = md5(md5($password) . $admin['salt']);
            $result = db('admin')->where(['id' => $admin['id']])->update(['password'=>$ps]);;
            if($result){

                write_admin_log('修改密码');
                return json(array('code' => '1', 'msg' => '修改成功'));
            }else{
                return json(array('code' => '0', 'msg' => '修改失败'));
            }
        }else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

    /**
     *  生成二维码 窗口
     *  1:保存文件流 for sendmail
     */
    public function create_Qrcode(){
        $com =new CommonPlus();
        $post = input('post.');
        $url = isset($post['url']) && $post['url'] != '' ? $post['url'] : null;
        $type = isset($post['type']) && $post['type'] != '' ? $post['type'] : null;
        $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
        if(empty($url)){
            return json(array('code' => '0', 'msg' => '缺少url参数'));
        }
        //展商邀请函使用二维码
        if($type == 2){
            $exhibition=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
            if(!$exhibition){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $url=($exhibition['project_id']== 21 ? 'https://h5.plfasia.com' : 'https://h5.fmrexpo.com').$url;
        }
        // 开始
        if($type == 0){
            $exhibition=db('exhibition')->where(['id'=>$exhibition_id,'is_delete'=>0])->find();
            $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
            $tabRes=db($exhibition['create_person_table'])->where(['person_id'=>$id])->find();
            if(!$exhibition){
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $url=$tabRes['is_cart'];
//            var_dump($tabRes['is_cart']);
//            var_dump($url);
        }
        $r=$com->createTempQrcode($url);

        if(!$r){
            return json(array('code' => '0', 'msg' => '生成二维码失败'));
        }
        if($type==1){
            // 存文件流
            $person_id = isset($post['person_id']) && $post['person_id'] != '' ? $post['person_id'] : null;
            $tbname1="poster_log";
            $where1 = array('exhibition_id' => $exhibition_id,'id_zs'=>$person_id);
            $r1=$com->sel_com_one('11', $where1, $tbname1);
            if(!$r1){
                $data2 =  array('exhibition_id' => $exhibition_id,'id_zs'=>$person_id,'imgebase'=>$r['data'],'create_time'=>time());
                $r2=$com-> insert_com_dan($data2,'22', $tbname1);
                if(!$r2){
                    return json(array('code' => '0', 'msg' => '保存文件流失败'));
                }
            }



        }
        return json(['code' => 1, 'msg' => '操作成功','data'=>$r]);

    }


    /**
         * 获取合同催款时间  设置为一个30天前
         *
         * @return void
         */
        public function getNewsList(){
            if (request()->isPost()) {
                $admin = session('admin');
                $admin = AdminModel::get(['id' => $admin['id']]);
                $post = input('post.');
                if (empty($admin)) {
                    return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
                }
                $sql="SELECT
                h.id as contracts_id,
                h.id_zs,
                h.id_zhui,
                h.name_zs,
                h.ht_time_endpay,
                h.money_total_ht,
                h.create_uid,
                z.create_tablename,
                f.f_total,
                z.title,
                n.*,
                a.realname
                FROM
                crm_contract AS h
                LEFT JOIN (SELECT SUM(fee) as f_total,contract_id FROM crm_finance WHERE is_delete=0 AND status>1 GROUP BY contract_id) AS f ON f.contract_id=h.id
                LEFT JOIN crm_exhibition AS z ON z.id = h.id_zhui
                LEFT JOIN crm_news AS n ON n.contract_id = h.id
                LEFT JOIN crm_admin AS a ON a.id = h.create_uid
                WHERE h.is_delete = 0 AND h.s_status = 1 AND h.ht_time_endpay>".(time()-86400*30)." AND (f.f_total IS NULL OR (f.f_total>0 AND (h.money_total_ht-f.f_total)>0)) ";
                //超级管理员看所有
                if($admin['is_super']!=1){
                    $sql.=" and h.create_uid =".$admin['id'];
                }
                 $sql.="  ORDER BY h.ht_time_endpay";
                 //var_dump($sql);die();
                $list=Db::query($sql);
                $noReadyList=[];$readyList=[];$delList=[];$onReadyNum=0;$readyNum=0;$delNum=0;
                foreach ($list as &$v) {
                    $v['surplus_time']=$v['ht_time_endpay']-time();
                    if($v['id']){
                        if($v['status']==1 && $v['is_delete']==0){
                            $readyList[]=$v;
                            $readyNum++;
                        }
                        if($v['status']==1 && $v['is_delete']==1){
                            $delList[]=$v;
                            $delNum++;
                        }
                    }else{
                        $noReadyList[]=$v;
                        $onReadyNum++;
                    }
                }
                return json(['code' => 1, 'msg' => '操作成功', 'data' => ['list'=>$list,'noReadyList'=>$noReadyList,'readyList'=>$readyList,'delList'=>$delList,'onReadyNum'=>$onReadyNum,'readyNum'=>$readyNum,'delNum'=>$delNum]]);
            } else {
                return json(array('code' => '0', 'msg' => '请求失败'));
            }
        }

        /**
         * 标记为已读
         *
         * @return void
         */

         public function newsReady(){
            if (request()->isPost()) {
                $admin = session('admin');
                $admin = AdminModel::get(['id' => $admin['id']]);
                $post = input('post.');
                if (empty($admin)) {
                    return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
                }
                //合同id
                $contract_id = isset($post['contract_id']) && $post['contract_id'] != '' ? $post['contract_id'] : null;
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
                if (!$contract_id) {
                    return json(array('code' => '0', 'msg' => '合同id为空'));
                }
                $contract=db('contract')->where(['id'=>$contract_id])->find();
                if(empty($contract)){
                    return json(array('code' => '0', 'msg' => '合同信息错误'));
                }
                if($contract['create_uid']!=$admin['id']){
                    return json(array('code' => '0', 'msg' => '您不是此消息的最终接受者不可进行此操作！'));
                }
                $data['update_time']=time();
                $data['create_uid']=$admin['id'];
                $data['status']=1;
                $result='';
                if($id){
                    $result=db('news')->where(['id'=>$id])->update($data);
                }else{
                    $data['create_time']=time();
                    $data['contract_id']=$contract_id;
                    $result=db('news')->insert($data);
                }
                if(!$result){
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                return json(array('code' => '1', 'msg' => '操作成功'));
            } else {
                return json(array('code' => '0', 'msg' => '请求失败'));
            }
         }


         /**
         * 删除消息
         *
         * @return void
         */
        public function newsDel(){
            if (request()->isPost()) {
                $admin = session('admin');
                $admin = AdminModel::get(['id' => $admin['id']]);
                $post = input('post.');
                if (empty($admin)) {
                    return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
                }
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
                if (!$id) {
                    return json(array('code' => '0', 'msg' => '主键不能为空'));
                }
                $news=db('news')->where(['id'=>$id])->find();
                if(empty($news)){
                    return json(array('code' => '0', 'msg' => '消息信息错误'));
                }
                if($news['create_uid']!=$admin['id']){
                    return json(array('code' => '0', 'msg' => '您不是此消息的最终接受者不可进行此操作！'));
                }
                $data['update_time']=time();
                $data['is_delete']=1;
                $result=db('news')->where(['id'=>$id])->update($data);
                if(!$result){
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                return json(array('code' => '1', 'msg' => '操作成功'));
            } else {
                return json(array('code' => '0', 'msg' => '请求失败'));
            }
        }

         /**
         * 还原消息
         *
         * @return void
         */
        public function newsRest(){
            if (request()->isPost()) {
                $admin = session('admin');
                $admin = AdminModel::get(['id' => $admin['id']]);
                $post = input('post.');
                if (empty($admin)) {
                    return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
                }
                $id = isset($post['id']) && $post['id'] != '' ? $post['id'] : null;
                if (!$id) {
                    return json(array('code' => '0', 'msg' => '主键不能为空'));
                }
                $news=db('news')->where(['id'=>$id])->find();
                if(empty($news)){
                    return json(array('code' => '0', 'msg' => '消息信息错误'));
                }
                if($news['create_uid']!=$admin['id']){
                    return json(array('code' => '0', 'msg' => '您不是此消息的最终接受者不可进行此操作！'));
                }
                $data['update_time']=time();
                $data['is_delete']=0;
                $result=db('news')->where(['id'=>$id])->update($data);
                if(!$result){
                    return json(array('code' => '0', 'msg' => '操作失败'));
                }
                return json(array('code' => '1', 'msg' => '操作成功'));
            } else {
                return json(array('code' => '0', 'msg' => '请求失败'));
            }
        }


    /**
     * 获取最大展商数量
     *
     * @return void
     */
    public function getCompanyMax(){
        if (request()->isPost()) {
            $admin = session('admin');
            $admin = AdminModel::get(['id' => $admin['id']]);
            $post = input('post.');
            if (empty($admin)) {
                return json(array('code' => '0', 'msg' => '请先登录或联系管理员注册账号'));
            }
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            if (!$exhibition_id) {
                return json(array('code' => '0', 'msg' => '展会信息错误'));
            }
            $max_number=db('max_number')->where(['uid'=>$admin['id'],'exhibition_id'=>$exhibition_id])->value('max_number');
            $max_number=$max_number?$max_number:30;
            return json(array('code' => '1', 'msg' => '操作成功','data'=>$max_number));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function remUnlink(){
        if (request()->isPost()) {
//            return json(array('code' => '1', 'msg' => '操作成功'));
            $post = input('post.');
            $dir_type = isset($post['dir_type']) && $post['dir_type'] != '' ? $post['dir_type'] : 1;
            $dirname = isset($post['dirname']) && $post['dirname'] != '' ? $post['dirname'] : '';
            if (!$dirname) {
                return json(array('code' => '0', 'msg' => '主键不能为空'));
            }
            $fail='';
            if($dir_type == 1){
                $fail=ROOT_PATH.'public/uploads/word/'+$dirname;
            }
            if(file_exists($fail)){
                unlink($fail);
            }
            return json(array('code' => '1', 'msg' => '操作成功'));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function sendStreamFile(){
        $post = input('post.');
        $dirname = isset($post['dirname']) && $post['dirname'] != '' ? $post['dirname'] : '';
        $filepath=ROOT_PATH.'public/contractTemp/20200708/5bed18f71352bb1b4a7169f93e2ca97f.pdf';
        $this->downloadFile($filepath);
        exit;
    }

    function downloadFile($filepath){
        $_file = pathinfo($filepath);
        if (!file_exists($filepath)){
            header("Content-type: text/html; charset=utf-8");
            echo "File not found!";
            exit;
        } else {
            $file = fopen($filepath,"r");
            Header("Content-type: application/octet-stream");
            Header("Accept-Ranges: bytes");
            Header("Accept-Length: ".filesize($filepath));
            Header("Content-Disposition: attachment; filename=".$_file['basename']);
            echo fread($file, filesize($filepath));
            fclose($file);
        }
    }


    //展会详情
    public function exhibitionDetail(){
        $exhibition_id = $this->request->param('exhibition_id');
        $exhibition=db('exhibition')->where(['is_delete'=>0,'id'=>$exhibition_id])->find();
        if(!$exhibition){
            return json(['code'=>0,'msg'=>'展会信息错误']);
        }
        return json(['code'=>1,'msg'=>'成功','data'=>$exhibition]);
    }


    public function threeLogin(){
        $host = "https://www.safety365.com.cn";
        $path = "/safety-server/companyProcessPipeline/app/selectOne/C98342114009739319";
        $method = "GET";
        $appcode = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjdXJyZW50VGltZU1pbGxpcyI6IjE2Mjk4MTEwODczOTEiLCJzb3VyY2UiOiJQQyIsImV4cCI6MTYyOTg5NzQ4Nywiand0X2FjY291bnQiOiLml6DplKHljY7nm5vmqaHog7bmlrDmnZDmlpnnp5HmioDogqHku73mnInpmZDlhazlj7gifQ.mOvIQGPZo2pLmcO9rZdWXVa0knqZd2KMHnXkWTfuXHg";
        $headers = array();
        array_push($headers, "jwt-token:" .$appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        $bodys = "";
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $data=curl_exec($curl);
        curl_close($curl);
        var_dump(json_decode($data,true));die();
        return (json_decode($data,true));
    }


    /**
     * 展会详情
     * @return \think\response\Json|void
     */
    public function detailExhibition()
    {
        $id = $this->request->param('id');
        $where['id'] = $id;
        $where['is_delete'] = 0;
        $info = db('exhibition')->where($where)->find();
        #展会信息
        $pavilion = db('pavilion')->where(['is_delete'=>0,'exhibition_id'=>$id])->select();
        $info['pavilion']=$pavilion;
        return json(['code' => 1, 'msg' => 'success', 'data' => $info]);
    }


    /**
     * 展会详情
     * @return \think\response\Json|void
     */
    public function historyExhibition()
    {
        $id = $this->request->param('id');
        $where['project_id'] = $id;
        $where['is_delete'] = 0;
        $list = db('exhibition')->where($where)->select();
        foreach ($list as &$v) {
            $pavilion = db('pavilion')->where(['is_delete'=>0,'exhibition_id'=>$id])->select();
            $info['pavilion']=$pavilion;
        }
        #展会信息
        return json(['code' => 1, 'msg' => 'success', 'data' => $list]);
    }

}
